﻿#region Copyright (c) Lokad 2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Runtime.Serialization;
using System.Xml;

namespace Lokad.Monitoring.Persistence.Serialization
{
    /// <summary>Overriding the <c>DataContractSerializer</c> with POX approach.</summary>
    public class PoxSerializer : XmlObjectSerializer
    {
        private DataContractSerializer _serializer;
        private bool _verifyObjectName;
        private Func<XmlReader, XmlReader> _createReader;
        private Func<XmlWriter, XmlWriter> _createWriter;

        public PoxSerializer(Type type)
        {
            _serializer = new DataContractSerializer(type);
            _verifyObjectName = false;
            _createReader = (r => new PoxXmlReader(r));
            _createWriter = (w => new PoxXmlWriter(w));
        }

        public override bool IsStartObject(XmlDictionaryReader reader)
        {
            return _serializer.IsStartObject(_createReader(reader));
        }

        public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
        {
            return _serializer.ReadObject(_createReader(reader), _verifyObjectName);
        }

        public override void WriteEndObject(XmlDictionaryWriter writer)
        {
            _serializer.WriteEndObject(_createWriter(writer));
        }

        public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
        {
            _serializer.WriteObjectContent(_createWriter(writer), graph);
        }

        public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
        {
            _serializer.WriteStartObject(_createWriter(writer), graph);
        }
    }

}
